package com.ug.config.filter;

import com.ug.common.enums.HttpCode;
import com.ug.common.exception.SystemException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.ug.common.utils.XssUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * @Author LY
 * @create 2024/7/17 15:42
 * @Description 统一基础拦截器
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(BaseInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (xssCheck(request)){
            throw new SystemException(HttpCode.XSS_PARAM_ERROR.getCode(), HttpCode.XSS_PARAM_ERROR.getMsg());
        }
        return true;
    }

    /**
     * xss校验
     * @param request 请求对象
     */
    private boolean xssCheck(HttpServletRequest request){
        //  检查参数
        Map<String, String[]> paramMap =  request.getParameterMap();
        for(String[] values:paramMap.values()){
            for(String value:values){
                if(XssUtils.checkXss(value)){
                    return true;
                }
            }
        }
        //  检查body
        String body = getBody(request);
        return XssUtils.checkXss(body);
    }

    private String getBody(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        try{
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }catch (IOException e){
            logger.error("BaseInterceptor.getBody|获取请求体异常:{}", e.getMessage());
        }
        return sb.toString();
    }
}
